package com.gaoxk.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Spring上下文持有类，用于在非Spring管理的类中获取Bean
 */
@Component
public class SpringContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    private  static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);
    private static int sum;

    /**
     * 实现ApplicationContextAware接口的回调方法，注入ApplicationContext
     */
    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        sum++;
        logger.info("SpringContextHolder sum:" + sum);
        logger.info(SpringContextHolder.class.getClassLoader().toString());
        applicationContext = context;
    }

    /**
     * 获取ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        logger.info("SpringContextHolder sum:" + sum);
        logger.info(SpringContextHolder.class.getClassLoader().toString());
        checkApplicationContext();
        return applicationContext;
    }

    /**
     * 根据Bean名称获取Bean
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }

    /**
     * 根据Bean类型获取Bean
     */
    public static <T> T getBean(Class<T> clazz) {
        checkApplicationContext();
        return applicationContext.getBean(clazz);
    }

    /**
     * 根据Bean名称和类型获取Bean
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        checkApplicationContext();
        return applicationContext.getBean(name, clazz);
    }

    /**
     * 清除ApplicationContext
     */
    public static void cleanApplicationContext() {
        applicationContext = null;
    }

    /**
     * 检查ApplicationContext是否已初始化
     */
    private static void checkApplicationContext() {
        if (applicationContext == null) {
            logger.error("Spring上下文未初始化，请检查Spring配置是否正确");
            throw new IllegalStateException("Spring上下文未初始化，请检查Spring配置是否正确");
        }
    }
}